package com.guit.hrms.verify.resume.impl;

import com.guit.hrms.verify.resume.AtLeastOneNotEmpty;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Field;

public class AtLeastOneNotEmptyValidator implements ConstraintValidator<AtLeastOneNotEmpty, Object> {

    private String[] fields;
    private Class<?> group;

    @Override
    public void initialize(AtLeastOneNotEmpty constraintAnnotation) {
        this.fields = constraintAnnotation.fields();
        this.group = constraintAnnotation.group();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (object == null) {
            return true; // 如果对象为空，跳过校验
        }

        try {
            for (String fieldName : fields) {
                Field field = object.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(object);

                // 如果至少有一个字段不为空，返回 true
                if (value != null && !value.toString().trim().isEmpty()) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果所有字段都为空，返回 false
        return false;
    }
}